<?php
/**
 * @notes:
 * @return
 * @author: admin
 * @date: 2024/9/10
 */


namespace addons\shopro\service\lucky;


use fast\Http;
use addons\shopro\service\commission\Agent as AgentService;
use addons\shopro\service\user\User as UserService;
use addons\shopro\service\Wallet;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\lucky\Agent;
use app\admin\model\shopro\lucky\Record;
use app\admin\model\shopro\user\User;
use think\Db;
use think\Exception;
use think\Log;

class RecordService
{


    protected $query = null;
    protected $format = null;

    public function __construct(\Closure $format = null, \think\db\Query $query = null)
    {
        $this->query = $query ?: new Record();
        $this->relationSearch = true;
        $this->format = $format;
    }

    /***
     * 获取充值记录
     * @notes:
     * @param $user
     * @return \think\Paginator
     * @throws \think\exception\DbException
     * @author: 小谢
     * @date: 2024/9/10 15:22
     */
    public function getList($user)
    {

        $list=$this->query->with('remittance')->where(['record.user_id'=>$user['id']])->order('id', 'desc')->paginate(request()->param('list_rows', 10));
        foreach ($list as $row) {
            $row->visible(['id','account','order_num','status','remark','createtime']);
            $row->visible(['remittance']);
            $row->getRelation('remittance')->visible(['name']);
        }
        return $list;

    }

    /***
     * 充值处理
     * @notes:
     * @param $prams
     * @param $user
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: 小谢
     * @date: 2024/9/10 13:56
     */
    public function payRecord($prams,$user)
    {
        if ($prams['online'] != 1) {
            $res=$this->query->where(['user_id'=>$user->id,'status'=>0])->find();
            if($res){
                error_stop('您已经有正在审核的充值订单，请等待完成后在申请！');
            }
        }
        $res=$this->query->where(['user_id'=>$user->id,'status'=>1])->max('account');

        if($res>0 && $prams['recharge_money']<3000 /*|| $res>0 && $prams['recharge_money']<$res*/){
            //error_stop('FT订单不能低于3000或上次数量');
            error_stop('FT订单不能低于3000');
        }

        //error_stop($res);

        Db::startTrans();
        try {
            $orderNo = 'PY'.get_sn($user->id);

            $data=[
                'order_num'=>$orderNo,
                'user_id'=>$user->id,
                'remittance_id'=>$prams['remittance_id'],
                'images'=>$prams['online'] ? '' : implode(',',$prams['images']),
                'account'=>$prams['recharge_money'],
                'online' => $prams['online']
            ];

            $this->query->save($data);

            //生成支付字符串
            $str = '';
            if ($prams['online'] == 1) {
                $str = $this->payStr($prams['recharge_money'], $orderNo);
            }

            Db::commit();
            return [
                'order_num' => $data['order_num'],
                'pay' => $str
            ];
        } catch (Exception $exception) {
            Db::rollback();
            error_stop($exception->getMessage());
        }
    }


    public function payStr($amount, $orderNo)
    {
        $arr = [
            "黄精口服液",
            "九华府黄精茶",
            "九华黄精酒",
            "精气神黄精原浆",
            "精气神黄精果",
            "黄精茶",
            "黄精口服液",
            "鹿心血花楸多肽片",
            "鹿肾褐藻多糖片",
            "鹿筋蛋白多肽片",
            "黄精口服液",
            "黄精茶",
            "好舒欣",
            "好舒欣",
            "天使舒适",
            "舒适天使",
            "丽之泉",
            "官喧福酒",
            "官喧福酒（箱）",
            "鹿产品套装",
            "御清净",
            "枸杞珍酒",
            "长白山人参",
            "盐掌门九烤竹盐",
            "五常大米",
            "快乐包礼盒",
            "陈皮酒",
            "纪沟灵芝孢子粉",
            "檀今朝酒",
            "牛蒡破壁粉",
            "牛蒡玉米羹",
            "田坤道贡米"
        ];

        $randomKey = array_rand($arr);

        $randomValue = $arr[$randomKey];

        $params = [];
        $amount = $amount * 100;
        $params['amount'] = "$amount";
        $params['body'] = $randomValue;
        $params['cashierType'] = 'MOVE';
        $params['currency'] = 'CNY';
        $params['mchNo'] = 'M25101000031';
        $params['mchOrderNo'] = $orderNo;
        $params['notifyUrl'] = 'http://140.143.163.115:81/addons/shopro/user.user/accountPay';
        $params['reqTime'] = (string)round(microtime(true) * 1000);
        $params['sellerRemark'] = '在线购买';
        $params['signType'] = 'MD5';
        $params['subject'] = '商户智能收银';
        $params['version'] = '2.0';
        ksort($params);
        $api_key= 'gxJZ2PB73gGOPq9uYTcmPQDnSGRU78JP1Z0v5hyAgde6nipJHNpxqZHjKRZkf74a0486zzwUcosnyuGs87h8fDX21NR53ruHIU2BvuTnVVWcuUboDm0XKmfPGPY588jn';
        $singStr = '';
        foreach ($params as $key => $value) {
            $singStr .= $key . '=' . $value . '&';
        }
        $singStr .= "key=".$api_key;
        $sign = strtoupper(md5($singStr));
        $params['sign'] = $sign;
        $ret = Http::httpJsonRequest('https://pay.wangfupay.com/api/v2/pay/unifiedOrder', $params);
        $ret = json_decode($ret,true);
        if ($ret['code'] != 0) {
            error_stop($ret['msg']);
        }
        return 'alipays://platformapi/startapp?appId=20000067&url='.urlencode($ret['data']['payUrl']);
    }

    /***
     * 处理订单状态
     * @notes:
     * @param $id
     * @param string $status
     * @return bool
     * @author: 小谢
     * @date: 2024/9/10 15:12
     */
    public function setStatus($id,$status='1')
    {
        Db::startTrans();
        try{
            $row=$this->query->get($id);
            if(!$row || $row['status']!='0'){
                Db::rollback();
                error_stop('此订单不存在或者已处理！');
            }
            $row->status=$status;
            $agent=null;
            if($status==='1'){
                WalletService::change($row->user_id,'balance',$row->account,'order_recharge');
                $user=User::where('id',$row->user_id)->find();
                UserService::consume($user, $row->account);
                $agent = new AgentService($user);
                $orderAgent = new \addons\shopro\service\commission\Agent($user->parent_user_id);
                if($orderAgent->isAgentAvaliable()){
                    $orderAgent->agent->setInc('child_order_money_1', $row->account);
                    $orderAgent->agent->setInc('child_order_count_1',1);
                    $orderAgent->agent->setInc('today_commission_mony', $row->account);
                }

            }
            $row->save();
            Db::commit();
            // 分销商数据统计&升级(异步执行)
            if($agent){
                $agent->createAsyncAgentUpgrade();
            }
            return true;
        }catch (\Exception $e){
            Db::rollback();
            error_stop($e->getMessage());
        }

    }

    public function getOrderByNo($orderNo)
    {
        return $this->query->where('order_num', $orderNo)->where('status', 0)->find();
    }



}